﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Google.Analytics.Model.Queries;

namespace Google.Analytics.Web.Converters
{
    public class SortConverter : CSVConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            // If source value is a Hand type
            if (value is Order[])
            {
                // Convert to string
                if ((destinationType == typeof(string)))
                {
                    var values = (Order[])value;
                    var sb = new StringBuilder();
                    foreach (var val in values)
                    {
                        sb.Append(val + ",");
                    }

                    return (sb.Length > 0) ? sb.ToString(0, sb.Length - 1) : string.Empty;
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            object val = base.ConvertFrom(context, culture, value);
            if(val is Array)
            {
                var orderItems = new List<Order>();
                foreach (var item in (string[])val)
                {
                    var order = (item.StartsWith("-")) ? SortDirection.Des : SortDirection.Asc;
                    var enumValue = (item.StartsWith("-")) ? item.Substring(1) : item;
                    Enum orderBy = null;
                    if (Enum.IsDefined(typeof(Metrics), enumValue)) orderBy = (Metrics)Enum.Parse(typeof(Metrics), enumValue);
                    if (Enum.IsDefined(typeof(Dimensions), enumValue)) orderBy = (Dimensions)Enum.Parse(typeof(Dimensions), enumValue);

                    if (orderBy != null) orderItems.Add(new Order(orderBy, order));
                } 
                return orderItems.ToArray();
            }
            return val;
        }
    }
}